﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ECCIT;
using ECCIT.Data;
using ECCIT.Business.Model;
using ECCIT.Business.DAL;

using OgilvyOne.Model;
using OgilvyOne.SqlServerDAL;
using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;

using System.Data;

namespace OgilvyOne.UKNow.DAL
{
    public class NewsUserDAL : UKNowBaseDAL,IDALNewsUser
    {
        private const string TBL_NAME            = "UKNOW_PRESS_DOWN";                  //表名
        private const string COL_LANG_ID         = "COL_LANG_ID";                       //语言类型
        private const string COL_USER_ID         = "COL_USER_ID";                       //用户ＩＤ
        private const string COL_USERNAME        = "COL_USERNAME";　　　　　　　　　　   //用户名
        private const string COL_PassWord        = "COL_PassWord";                       //密码
        private const string COL_STATUS          = "COL_STATUS";                         //状态
        private const string COL_CreatTime       = "COL_CreatTime";                      //创建时间

        public override string TableName { get { return TBL_NAME; } }

        public override Type ModelType { get { return typeof(NewsUserModel); } }
        [PrimaryKey]
        public IField LanguageID { get { return FieldFactory.Create(ModelType, "LanguageID", ColumnFactory.CreateColumn(COL_LANG_ID, DataType.Int)); } }
        [PrimaryKey]
        public IField ID { get { return FieldFactory.Create(ModelType, "ID", ColumnFactory.CreateColumn(COL_USER_ID, DataType.Int)); } }
        public IField Name { get { return FieldFactory.Create(ModelType, "Name", ColumnFactory.CreateColumn(COL_USERNAME, DataType.String)); } }
        public IField Password { get { return FieldFactory.Create(ModelType, "Password", ColumnFactory.CreateColumn(COL_PassWord, DataType.String)); } }
        public IField Status { get { return FieldFactory.Create(ModelType, "Status", ColumnFactory.CreateColumn(COL_STATUS, DataType.Int)); } }
        public IField CreatTime { get { return FieldFactory.Create(ModelType, "CreatTime", ColumnFactory.CreateColumn(COL_CreatTime, DataType.String)); } }


        public override IField[] InsertFields { get { return new IField[] { LanguageID, ID, Name, Password, Status, CreatTime }; } }
        public override IField[] SelectFields { get { return new IField[] { LanguageID, ID, Name, Password, Status, CreatTime }; } }
        public override IField[] UpdateFields { get { return new IField[] { LanguageID, Name, Password, Status, CreatTime }; } }

        public NewsUserDAL() { }

        public NewsUserDAL(LanguageType languageType) { this.Language = LanguageFactory.Create(languageType); }

        private void SetForeignKeyModel(NewsUserModel model)
        {
            if (model == null) return;
        }

        #region IDALNewsUser Members
        /// <summary>
        /// 保存/修改数据
        /// </summary>
        /// <param name="modelInfo">新闻用户实体类</param>
        /// <returns>ResultInfo</returns>
        public ResultInfo Save(NewsUserModel modelInfo)
        {
            if (modelInfo == null) throw new ArgumentNullException("modelInfo");

            ResultInfo result = new ResultInfo(false);

            try
            {
                int rowsAffected = 0;
                if (modelInfo.ID == null)   // insert
                {
                    modelInfo.ID = SqlUtil.GetMaxRecordID(TableName, COL_USER_ID, COL_LANG_ID, (int)this.Language.LanguageType);
                    modelInfo.Status = 1;    // 强制将用户状态置为有效
                    modelInfo.CreatTime = DateTime.Now.ToString();
                    rowsAffected = Insert(modelInfo, null);
                }
                else // update
                {
                    rowsAffected = UpdateByPrimaryKey(modelInfo, null);
                }

                if (rowsAffected > 0)
                {
                    result.Message = "活动数据保存成功！";
                    result.Result = true;
                    result.ReturnObject = modelInfo;
                }
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = string.Format("保存数据时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        /// <summary>
        /// 设置用户是否有效 
        /// </summary>
        /// <param name="id">用户id</param>
        /// <param name="flag">标识位 真值：有效 假值：无效</param>
        /// <returns></returns>
        public ResultInfo SetStatus(int id,bool flag)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.Status };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            if (flag)
                parms[0].Value = 1; //有效
            else
                parms[0].Value = 0; //无效

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_USER_ID, DataType.Int, id));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "设置成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("设置状态时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        /// <summary>
        /// 获取所有用户数据
        /// </summary>
        /// <returns>返回泛型集合</returns>
        public IList<NewsUserModel> GetNewsUserModel()
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            IList<NewsUserModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(CreatTime.PropertyName, SortOrder.Desc))).List.Cast<NewsUserModel>().ToList();
            return models;
        }

        /// <summary>
        ///  根据用户id获取该对象的实体
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns>返回该对象的实体</returns>
        public NewsUserModel GetNewsUserModelByID(int? id)
        {
            NewsUserModel model = (NewsUserModel)GetModelByPrimaryKey(this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });
            return model;
        }

        /// <summary>
        ///  验证用户名是否重复
        /// </summary>
        /// <param name="name">用户名</param>
        /// <returns>返回该对象的实体或null</returns>
        public IList<NewsUserModel> CheckName(string name)
        {
            string whereClause = string.Format("where {0}='{1}' ", COL_USERNAME, name);
            return GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(CreatTime.PropertyName, SortOrder.Desc))).List.Cast<NewsUserModel>().ToList();

        }

        #endregion
    }
}
